from myApp.model.db import db
from sqlalchemy import Column, BigInteger, String, DateTime, func


class User(db.Model):
    __tablename__ = 'user'

    id = Column(BigInteger, primary_key=True, autoincrement=True)
    nickname = Column(String(255), nullable=True)
    account = Column(String(255), nullable=False, unique=True)
    password = Column(String(255), nullable=True)
    role = Column(String(255), nullable=False, default='user/administrator')
    create_time = Column(DateTime, default=func.now(), nullable=False)
    update_time = Column(DateTime, default=func.now(), onupdate=func.now(), nullable=False)
    ent_user_id = Column(String(100), nullable=True, comment='主系统用户id')

    def __repr__(self):
        return f"<User(id={self.id}, nickname={self.nickname}, account={self.account}, role={self.role}, ent_user_id={self.ent_user_id})>"

    # serialize
    def serialize(self):
        return {
            'id': self.id,
            'nickname': self.nickname,
            'account': self.account,
            'role': self.role,
            'ent_user_id': self.ent_user_id,
            'create_time': self.create_time.strftime('%Y-%m-%d %H:%M:%S'),
            'update_time': self.update_time.strftime('%Y-%m-%d %H:%M:%S')
        }

    # 根据账户名获取用户信息
    @staticmethod
    def get_user_by_account(account):
        user = User.query.filter_by(account=account).first()
        return user

    # 根据id获取用户信息
    @staticmethod
    def get_user_by_id(user_id):
        user = User.query.filter_by(id=user_id).first()
        return user

    # 根据ent_user_id获取用户信息
    @staticmethod
    def get_user_by_ent_user_id(ent_user_id):
        user = User.query.filter_by(ent_user_id=ent_user_id).first()
        return user

    # 创建用户
    @staticmethod
    def create_user(nickname, account, password, role, ent_user_id=None):
        user = User(nickname=nickname, account=account, password=password, role=role, ent_user_id=ent_user_id)
        db.session.add(user)
        db.session.commit()
        return user
